package com.example.dryyzx.controller;

import com.example.dryyzx.dao.*;
import com.example.dryyzx.encapsulation.LeavePageEncapsulation;
import com.example.dryyzx.encapsulation.LeavePageEncapsulation2;
import com.example.dryyzx.encapsulation.LeavePageEncapsulation3;
import com.example.dryyzx.entity.Bed;
import com.example.dryyzx.entity.Checkout;
import com.example.dryyzx.entity.Customer;
import com.example.dryyzx.entity.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class CheckoutController {

    @Autowired
    private CheckoutMapper checkoutMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private BedRecordMapper bedRecordMapper;
    @Autowired
    private OrderMapper orderMapper;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    List<LeavePageEncapsulation2> changeForm(List<LeavePageEncapsulation> encapsulation,int limit){
        List<LeavePageEncapsulation2> encapsulation2=new ArrayList<LeavePageEncapsulation2>();
        for(int i=0;i<limit;i++){
            LeavePageEncapsulation2 tmp = new LeavePageEncapsulation2();
            tmp.id=encapsulation.get(i).id;//退住单号
            tmp.name=encapsulation.get(i).name;//客户姓名
            tmp.gender=encapsulation.get(i).gender;//性别
            tmp.age=encapsulation.get(i).age;//年龄
            tmp.file_number=encapsulation.get(i).file_number;//档案号
            tmp.checkin_date=sdf.format(encapsulation.get(i).checkin_date);//入住日期
            tmp.leave_date=sdf.format(encapsulation.get(i).leave_date);//退住日期
            tmp.type=encapsulation.get(i).type;//退住类型（'正常退住'、'亡故退住'、'保留床位'）
            tmp.reason=encapsulation.get(i).reason;//退住原因
            tmp.leave_status=encapsulation.get(i).leave_status;//退住状态
            tmp.apply_date=sdf.format(encapsulation.get(i).apply_date);//申请日期
            if(encapsulation.get(i).approval_date!=null)
                tmp.approval_date=sdf.format(encapsulation.get(i).approval_date);//审核日期
            tmp.approver=encapsulation.get(i).approver;//审核人
            tmp.remark=encapsulation.get(i).remark;//备注
            encapsulation2.add(i, tmp);
        }
        return encapsulation2;
    }

    @RequestMapping(value = "leave_page/search_leave_record_by_name", method = RequestMethod.POST)
    public @ResponseBody
    String search_checkout_by_name(String search_name, int page, HttpSession session) {
        int data_per_page = 10;
        List<LeavePageEncapsulation> leavePageEncapsulation = checkoutMapper.selectCheckoutCustomerByName(search_name);

        int total_data_no = leavePageEncapsulation.size();
        if(total_data_no<=0)
            return new JsonResult(false, "未查找到退住记录").toString();

        int offset=(page-1)*data_per_page;
        int limit;
        if(total_data_no-offset<data_per_page)
            limit=total_data_no-offset;
        else
            limit=data_per_page;
        if(total_data_no<=offset)
            return new JsonResult(false, "页数过大，数据不够").toString();

        for(int i=0;i<offset;i++)
            leavePageEncapsulation.remove(0);
        while(leavePageEncapsulation.size()>limit)
            leavePageEncapsulation.remove(limit);

        LeavePageEncapsulation3 total_data=new LeavePageEncapsulation3();
        List<LeavePageEncapsulation2> leavePageEncapsulation2=changeForm(leavePageEncapsulation,limit);
        total_data.checkout_list=leavePageEncapsulation2;
        total_data.total_page=(total_data_no-1)/data_per_page+1;

        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "leaveapproval_page/getLeave", method = RequestMethod.POST)
    public @ResponseBody
    String search_unapproved_checkout_by_name( String search_name, int page, HttpSession session) {
        int data_per_page = 10;
        List<LeavePageEncapsulation> leavePageEncapsulation = checkoutMapper.selectUnapprovedCheckoutCustomerByName(search_name);

        int total_data_no = leavePageEncapsulation.size();
        if(total_data_no<=0)
            return new JsonResult(false, new LeavePageEncapsulation3()).toString();

        int offset=(page-1)*data_per_page;
        int limit;
        if(total_data_no-offset<data_per_page)
            limit=total_data_no-offset;
        else
            limit=data_per_page;
        if(total_data_no<=offset)
            return new JsonResult(false, "页数过大，数据不够").toString();

        for(int i=0;i<offset;i++)
            leavePageEncapsulation.remove(0);
        while(leavePageEncapsulation.size()>limit)
            leavePageEncapsulation.remove(limit);

        LeavePageEncapsulation3 total_data=new LeavePageEncapsulation3();
        List<LeavePageEncapsulation2> leavePageEncapsulation2=changeForm(leavePageEncapsulation,limit);
        total_data.checkout_list=leavePageEncapsulation2;
        total_data.total_page=(total_data_no-1)/data_per_page+1;

        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "leave_page/new_leave_record",method = RequestMethod.POST)
    public @ResponseBody String addCheckout(String name,String identify_number,String reason,String type,String date,
                                      String remark) throws ParseException {
        Customer customer = new Customer();
        customer = customerMapper.selectByNameIdNumber(name,identify_number);
        if(customer==null)
            return new JsonResult(false, "找不到要退住的老人或老人已退住").toString();

        Checkout checkout = new Checkout();
        checkout.setCustomerId(customer.getId());
        checkout.setType(type);
        checkout.setReason(reason);
        checkout.setCheckoutTime(sdf.parse(date));
        Date currentDate=new Date();
        checkout.setApplyTime(currentDate);
        checkout.setLeaveStatus("未审核");
        checkout.setRemarks(remark);
        checkout.setEnable(true);

        int insert = checkoutMapper.insertSelective(checkout);
        if(insert == 0)
            return new JsonResult(false, "找到老人，但无法申请退住").toString();
        return new JsonResult(true, insert).toString();
    }

    @RequestMapping(value = "leave_page/change_leave_record",method = RequestMethod.POST)
    public @ResponseBody String changeCheckout(int id,String reason,String type,String date, String remark) throws ParseException {
        Checkout checkout = new Checkout();
        checkout.setId(id);
        checkout.setReason(reason);
        checkout.setType(type);
        checkout.setCheckoutTime(sdf.parse(date));
        checkout.setRemarks(remark);

        int update =checkoutMapper.updateByPrimaryKeySelective(checkout);
        if(update == 0)
            return new JsonResult(false, "无法修改退住记录").toString();
        return new JsonResult(true, update).toString();
    }

    @RequestMapping(value = "leaveapproval_page/approvalNo",method = RequestMethod.POST)
    public @ResponseBody String disapproveCheckout(int id,String uname) throws ParseException {
        Checkout check = checkoutMapper.selectByIdEnable(id);
        if(check ==null)
            return new JsonResult(false, "找不到要审核的退住记录").toString();
        if(check.getLeaveStatus().equals("未审核"));
        else
            return new JsonResult(false, "记录已审核").toString();

        Checkout checkout = new Checkout();
        checkout.setId(id);
        Date currentDate=new Date();
        checkout.setApprovalTime(currentDate);
        checkout.setApprover(uname);
        checkout.setLeaveStatus("已审核未通过");

        int update =checkoutMapper.updateByPrimaryKeySelective(checkout);
        if(update == 0)
            return new JsonResult(false, "无法审核该退住记录").toString();
        return new JsonResult(true, update).toString();
    }

    @RequestMapping(value = "leaveapproval_page/approvalYes",method = RequestMethod.POST)
    public @ResponseBody String approveCheckout(int id,String uname) throws ParseException {
        Checkout currentCheckout = checkoutMapper.selectByIdEnable(id);
        if(currentCheckout ==null)
            return new JsonResult(false, "找不到要审核的退住记录").toString();
        if(currentCheckout.getLeaveStatus().equals("未审核"));
        else
            return new JsonResult(false, "记录已审核").toString();

        Checkout checkout = new Checkout();
        checkout.setId(id);
        Date currentDate=new Date();
        checkout.setApprovalTime(currentDate);
        checkout.setApprover(uname);
        checkout.setLeaveStatus("已审核通过");

        Customer currentCustomer = customerMapper.selectByPrimaryKey1(currentCheckout.getCustomerId());
        if(currentCustomer ==null)
            return new JsonResult(false, "找不到要审核退住记录的老人").toString();
        if(currentCustomer.getState().equals("已退住"))
            return new JsonResult(false, "该记录的老人已退住").toString();

        Customer customer = new Customer();
        customer.setId(currentCheckout.getCustomerId());
        customer.setState("已退住");

        Bed currentBed = bedMapper.selectByPrimaryKey(currentCustomer.getBedId());
        if(currentBed ==null)
            System.out.println("找不到老人的床");
        if(currentBed.getIsOccupied() ==false)
            System.out.println("老人的床未被占用");

        Bed bed =new Bed();
        bed.setId(currentCustomer.getBedId());
        bed.setIsOccupied(false);

        int update1 =checkoutMapper.updateByPrimaryKeySelective(checkout);
        int update2 =customerMapper.updateByPrimaryKeySelective(customer);
        int update3 =bedMapper.updateByPrimaryKeySelective(bed);
        int update4 =bedRecordMapper.disableByCustomerId(currentCheckout.getCustomerId());
        int update5 =orderMapper.disableByCustomerId(currentCheckout.getCustomerId());
        if(update1 == 0 || update2 == 0 || update3 == 0 )
            return new JsonResult(false, "无法通过该退住记录").toString();
        return new JsonResult(true, update1).toString();
    }
}
